package examples.session.stateless;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptors;
import javax.interceptor.InvocationContext;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import examples.interceptor.AuditorInterceptor;
import examples.interceptor.LoggerInterceptor;

/**
 * Session Bean implementation class PricerBean
 */
@Stateless
@Interceptors({LoggerInterceptor.class,AuditorInterceptor.class})
public class PricerBean implements Pricer {

	private TaxRate taxRate;

	@EJB
	private TaxRate taxRate2;

	public double getTaxLookup(double cost, String state) {
		System.out.println("getTaxLookup()");
		double tax = -1;
		tax = cost * taxRate.getTaxRate(state);
		return tax;
	}

	public double getTaxInjection(double cost, String state) {
		System.out.println("getTaxInjection()");
		double tax = -1;
		tax = cost * taxRate2.getTaxRate(state);
		return tax;
	}

	@PostConstruct
	public void postConstruct() {
		try {
			InitialContext ic = new InitialContext();
			taxRate = (TaxRate) ic.lookup("TaxRateBean/remote");
//			taxRate = (TaxRate) ic.lookup("TaxRate");
//			taxRate = (TaxRate) ic.lookup("TaxRateBean");
//			taxRate = (TaxRate) ic.lookup(TaxRate.class.getName());
		} catch (NamingException e) {
			// some kind of appropriate handling here
			System.out.println("Error initializing taxRate Bean");
			e.printStackTrace();
		}
	}

	@PreDestroy
	public void preDestroy() {
		taxRate = null;
	}

	@AroundInvoke
	public Object logger(InvocationContext inv) throws Exception {
		System.out.println("logger() - Intercepted call via internal method to: "
				+ inv.getMethod().getName());
		Object[] params = inv.getParameters();
		for (int i = 0; i < params.length; i++) {
			System.out.println("\tparam: " + params[i]);
		}
		return inv.proceed();
	}
}
